package jp.co.jbuy.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.co.jbuy.action.ActionManager;
import jp.co.jbuy.action.BaseAction;
import jp.co.jbuy.common.ConnectionManager;
import jp.co.jbuy.common.ResourceManager;
import jp.co.jbuy.common.MessageManager;


public class MainServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private ActionManager pm_ = new ActionManager();
	private static ConnectionManager connManager_;

	
	public void init(ServletConfig config) throws ServletException{
		System.out.println("■init():start");
		super.init(config);
		ResourceBundle res = ResourceBundle.getBundle("resource");
		ResourceManager.setCurrentBundle(res);
		setConnection(res);
		connManager_.getConnection();
		try {
			MessageManager.loadAll(connManager_.getConnection());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("■init():end");

	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
												throws ServletException, IOException{	
		
		Connection conn=null;
		try {
			ResourceBundle res = ResourceBundle.getBundle("resource");
			ResourceManager.setCurrentBundle(res);
			conn= connManager_.getConnection();
			BaseAction page = pm_.createPage(request);
			page.prepare(conn, request, response, res);
			page.action();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}finally {
			if(conn!=null)
				try {
					conn.commit();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			if(conn!=null)
			{
				connManager_.release(conn);
			}
		}
	}
	

	public void destroy() {
		
	}
	
	private void setConnection(ResourceBundle res){
		connManager_ = null;
		connManager_ = new ConnectionManager(res.getString("jdbc.driver"),
				res.getString("jdbc.url"),
				res.getString("jdbc.username"),
				res.getString("jdbc.password"),
				Integer.parseInt(res.getString("jdbc.connectionPoolMax")),
				false, res.getString("jdbc.transaction_isolation"));
	}
	
	public void releaseAllConnections() {
		connManager_.releaseAll();
	}
}
